package io.renren.modules.app.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.utils.R;
import io.renren.modules.app.entity.company.YcCollectCompany;
import io.renren.modules.app.entity.index.YcSpreadEntity;
import io.renren.modules.app.entity.info.YcUserInterview;
import io.renren.modules.app.entity.info.YcUserPost;
import io.renren.modules.app.entity.user.UserEntity;
import io.renren.modules.app.entity.user.UserResumeEntity;
import io.renren.modules.app.service.index.YcUserFeedbackService;
import io.renren.modules.app.service.user.UserResumeService;
import io.renren.modules.app.service.user.UserService;
import io.renren.modules.app.utils.ALiSMSUtil;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.time.LocalDate;
import java.util.*;

@RestController
@RequiredArgsConstructor
@RequestMapping("user")
public class UserController {

    public static Map<String,Object> phoneMap = new HashMap<>();

    @Autowired
    private UserService userService;

    @Autowired
    private UserResumeService userResumeService;
    @ApiOperation("查询个人简历是否为空")
    public int selectUserResume(Integer userId) {
        QueryWrapper<UserResumeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        UserResumeEntity userResume = userResumeService.getOne(queryWrapper);
        return (userResume == null) ? 0 : 1;
    }

    /**
     * 通过userId查询用户信息
     */
    @GetMapping("/getUserInfo/{userId}")
    public R getUserInfo(@PathVariable("userId") Integer userId) {
        UserResumeEntity user = userResumeService.selectListByUserId(userId).get(0);
        int count = userResumeService.selectUserPostByUserId(userId).size();
        return R.ok().put("user", user).put("post", count);
    }

    /**
     * 通过userId查询投递信息
     */
    @GetMapping("/getUserPost/{userId}")
    public R getUserPost(@PathVariable("userId") Integer userId) {
        List<YcUserPost> userPosts = userResumeService.selectUserPostByUserId(userId);
        return R.ok().put("post", userPosts);
    }

    /**
     * 通过conpanyId查询投递信息
     */
    @GetMapping("/getCompanyPost/{companyId}")
    public R getCompanyPost(@PathVariable("companyId") Integer companyId) {
        List<YcUserPost> userPosts = userResumeService.selectCompanyPostById(companyId);
        return R.ok().put("post", userPosts);
    }

    /**
     * 通过companyId查询投递信息
     */
    @GetMapping("/getCompanyPostCount/{companyId}")
    public R getCompanyPostCount(@PathVariable("companyId") Integer companyId) {
        List<YcUserPost> userPosts = userResumeService.selectCompanyPostById(companyId);
        List<YcCollectCompany> collectCompanies = userResumeService.queryCollectCompanyByCompanyId(companyId);
        return R.ok().put("post", userPosts.size()).put("collects", collectCompanies.size());
    }

    /**
     * 更新简历查看状态
     */
    @GetMapping("/updateCompanyPostStatus/{postId}")
    public R updateCompanyPostStatus(@PathVariable("postId") Integer postId) {
        return R.ok().put("bool", userResumeService.updateCompanyPostStatus(postId));
    }

    /**
     * 新增企业收藏数据
     */
    @RequestMapping("/save/company/collect")
    public R saveCollectCompany(@RequestBody YcCollectCompany company){
        return R.ok().put("data", userResumeService.saveCollectCompany(company));
    }

    /**
     * 查询企业收藏状态
     */
    @RequestMapping("/query/company/collect")
    public R queryCollectCompany(@RequestParam("companyId") Integer companyId,
            @RequestParam("resumeId") Integer resumeId){
        return R.ok().put("data", userResumeService.exitsCollectCompany(companyId, resumeId));
    }

    /**
     * 查询企业收藏数据
     */
    @RequestMapping("/query/company/collect/list")
    public R queryCollectCompanyList(@RequestParam("companyId") Integer companyId){
        return R.ok().put("data", userResumeService.selectCompanyCollectList(companyId));
    }

    /**
     * 删除企业收藏数据
     */
    @RequestMapping("/delete/company/collect")
    public R deleteCollectCompany(@RequestParam("companyId") Integer companyId,
            @RequestParam("resumeId") Integer resumeId){
        return R.ok().put("data", userResumeService.deleteCollectCompany(companyId, resumeId));
    }

    /**
     * 查询企业收藏数据
     */
    @RequestMapping("/query/company/recuit/list")
    public R selectCompanyRecuitList(@RequestParam("companyId") Integer companyId){
        return R.ok().put("data", userResumeService.selectCompanyRecuitList(companyId));
    }

    /**
     * 新增约邀
     */
    @RequestMapping("/save/user/inter")
    public R saveUserInterview(@RequestBody YcUserInterview userInterview){
        return R.ok().put("data", userResumeService.saveUserInterview(userInterview));
    }

    /**
     * 查询是否已经约邀
     */
    @RequestMapping("/exits/user/inter")
    public R exitsUserInterview(@RequestParam("companyId") Integer companyId,
            @RequestParam("resumeId") Integer resumeId, @RequestParam("recrutId") Integer recrutId){
        return R.ok().put("data", userResumeService.selectCompanyInterList(companyId, resumeId, recrutId).size() > 0);
    }

    /**
     * 查询约邀数量
     */
    @RequestMapping("/get/company/inter/count")
    public R getCompanyInterviewSize(@RequestParam("companyId") Integer companyId){
        return R.ok().put("data", userResumeService.selectCompanyInterList(companyId, "").size());
    }

    /**
     * 查询约邀数量-用户
     */
    @RequestMapping("/get/user/inter/count")
    public R getUserInterviewSize(@RequestParam("userId") Integer userId){
        return R.ok().put("count", userResumeService.selectUserInterList(userId, "").size());
    }

    /**
     * 查询面试-用户
     */
    @RequestMapping("/get/user/inter/list")
    public R getUserInterviewList(@RequestParam("userId") Integer userId, @RequestParam("status") String status){
        return R.ok().put("list", userResumeService.selectUserInterList(userId, status));
    }

    private final YcUserFeedbackService ycUserFeedbackService;

    /**
     * 查询面试-公司
     */
    @RequestMapping("/get/company/inter/list")
    public R getCompanyInterviewList(@RequestParam("companyId") Integer companyId, @RequestParam("status") String status){
        List<YcUserInterview> userInterviews =
                userResumeService.selectCompanyInterList(companyId, status);
        if (userInterviews.size() > 0) {
            userInterviews.forEach(userInterview -> {
                boolean bool = ycUserFeedbackService.queryExitsUserFeedStatus(userInterview.getResumeId(),
                        userInterview.getRecruitId());
                userInterview.setFeedback(bool);
            });
        }
        return R.ok().put("list", userInterviews);
    }

    @RequestMapping("/update/inter/status")
    public R updateCompanyInterviewList(@RequestParam("id") Integer id, @RequestParam("status") String status){
        return R.ok().put("data", userResumeService.updateInterStatus(id, status));
    }

    @RequestMapping("/get/spread/consume/points")
    public R getSpreadConsumePoints () {
        return R.ok().put("data", userResumeService.getConsumePoints());
    }

    @RequestMapping("/save/spread/record")
    public R saveSpread (@RequestParam("companyId") String companyId) {
        if (StringUtils.isNotEmpty(companyId)) {
            return R.ok().put("data", userResumeService.saveSpreadRecord(Integer.parseInt(companyId)));
        }
        return R.ok().put("data", false);
    }

    @RequestMapping("/update/spread/status")
    public R updateSpreadStatus (@RequestParam("companyId") String companyId,
                                 @RequestParam("status") Integer status) {
        if (StringUtils.isNotEmpty(companyId)) {
            return R.ok().put("data", userResumeService.
                    updateStatusSpreadRecord(Integer.parseInt(companyId), status));
        }
        return R.ok().put("data", false);
    }

    @RequestMapping("/get/spread/status")
    public R getSpreadStatus (@RequestParam("companyId") String companyId) {
        if (StringUtils.isNotEmpty(companyId)) {
            return R.ok().put("data", userResumeService.exitsSpreadRecord(Integer.parseInt(companyId)));
        }
        return R.ok().put("data", false);
    }

    @RequestMapping("/get/spread/status2")
    public R getSpreadStatus2 (@RequestParam("companyId") String companyId) {
        if (StringUtils.isNotEmpty(companyId)) {
            return R.ok().put("data", userResumeService.checkSpreadStatus(Integer.parseInt(companyId)));
        }
        return R.ok().put("data", false);
    }

    /**
     * 更新用户信息
     */
    @PostMapping("/updateUserInfo")
    public R updateUserInfo(@RequestBody UserEntity user) {
        String mobile = user.getMobile();
        String age = user.getAge();
        if (StringUtils.isNotEmpty(user.getUserPortrait())) {
            String image = user.getUserPortrait();
            if (image.length() > 100) {
                String filename = saveImage(image);
                user.setUserPortrait(filename);
                filename = filename.split("/")[1];
                saveImageTarget(image, filename);
            }
        }
        userService.updateById(user);

        List<UserResumeEntity> userResumeEntityList = userResumeService.selectListByUserId(user.getId());
        if (userResumeEntityList.size() > 0) {
            for (UserResumeEntity entity : userResumeEntityList) {
                UserResumeEntity userResumeEntity = userResumeService.selectOneByUserId(entity.getId());
                userResumeEntity.setBirthdate(user.getBirthdate());
                userResumeEntity.setSex(user.getSex());
                userResumeEntity.setWechat(user.getWeixin());
                userResumeEntity.setTel(mobile);
                userResumeEntity.setAge(Integer.valueOf(age));
                userResumeEntity.setEmail(user.getEmail());
                userResumeEntity.setUserName(user.getUserName());
                userResumeEntity.setResumePortrait(user.getUserPortrait());
                userResumeService.updateById(userResumeEntity);

            }
        }
        return R.ok();
    }

    /*文件存储地址*/
    @Value("${file.save-path}")//yml的文件上传路径
    private String UPLOAD_SAVE_PATH;

    @Value("${file.target-path}")
    private String UPLOAD_TARGET_PATH;

    /**
     * 生成文件
     */
    private void saveImageTarget (String base64, String filename) {
        if (StringUtils.isNotEmpty(base64) && StringUtils.isNotEmpty(filename)) {
            byte[] decodedBytes = Base64.getDecoder().decode(base64);
            //组装存储路径
            String property = System.getProperty("file.separator");
            String parent_path = LocalDate.now().toString();
            //存贮至编译文件。前端可以直接访问。存到target下面的static的upload下
            String saveFilePath = (UPLOAD_TARGET_PATH + "/" + parent_path + "/").replaceAll("//", property);
            //检测文件路径是否存在
            if (!new File(saveFilePath).exists()) {
                new File(saveFilePath).mkdirs();
            }
            //生成文件名称
            String savePath = (saveFilePath + filename).replaceAll("//", property);
            try (OutputStream out = Files.newOutputStream(new File(savePath).toPath())) {
                out.write(decodedBytes);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 生成文件
     */
    private String saveImage (String base64) {
        if (StringUtils.isNotEmpty(base64)) {
            byte[] decodedBytes = Base64.getDecoder().decode(base64);//获取base64后转成字节
            //组装存储路径
            String property = System.getProperty("file.separator");//获取系统的路径符号，window是/
            String parent_path = LocalDate.now().toString();//获取当前时间作为文件夹
            String saveFilePath = (UPLOAD_SAVE_PATH + "/" + parent_path + "/").replaceAll("//", property);//拼装文件磁盘存储路径
            //检测文件路径是否存在
            if (!new File(saveFilePath).exists()) {
                new File(saveFilePath).mkdirs();//不存在该路径就创建
            }
            //生成文件名称
            String filename = System.currentTimeMillis() + ".jpg";
            String savePath = (saveFilePath + filename).replaceAll("//", property);//拼装完整的存储路径含有文件名和文件格式
            try (OutputStream out = Files.newOutputStream(new File(savePath).toPath())) {//通过文件流把文件写入到系统文件里
                out.write(decodedBytes);
                return  parent_path + "/" + filename;//fan
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 用户登录
     * @param map
     * @return
     */

    @PostMapping("/loginUser")//加入判断密码是否错误
    public R loginUser(@RequestParam Map<String, Object> map){
        Map<String,Object> result = userService.login(map);
        Integer code = (Integer) result.get("code");
        if(code == 200) {
            int userResume = selectUserResume(Integer.valueOf(result.get("userId").toString()));
            result.put("userResume", userResume);
        }
        return R.ok().put("result", result);
    }

    /**
     * 用户登录（理解而写的内容）
     * @return
     */
//
//    @PostMapping("/loginUser/test")
//    public R loginUser1(String username, String password){
////        String = "{\n" +
////                "    \t\tloginAccountName: 123,\n" +
////                "    \t\tloginPassword: 123\n" +
////                "    \t}"
//        HashMap<String, Object> map = new HashMap<>();
//        map.put("loginAccountName", "123");
//        map.put("loginPassword", "123");
//        return this.loginUser(map);
//    }


    /**
     * 快捷登录
     * @param map
     * @return
     */
    @PostMapping("/loginMobile")
    public R loginMobile(@RequestParam Map<String, Object> map){
        //初始化返回值
        Map<String, Object> result = new HashMap<>();
        //获取手机号
        String mobile= map.get("mobile").toString();
        System.out.println(mobile);
        //获取验证码
        String code = map.get("code").toString();

        //QueryWrapper <UserEntity> wrapper= new QueryWrapper<>();
        //getOne是底层的一个查询方法

        UserEntity users =  userService.getOne(new QueryWrapper<UserEntity>().eq("mobile",mobile));
        //users不为空，即该用户已经注册过
        if(users == null){
            result.put("code",500);
            result.put("msg","该手机号未注册");
            return R.ok().put("result", result);
        }
        try{
            String concode = phoneMap.get(mobile).toString();
            if(code.equals(concode)){
                result.put("code",200);
                result.put("msg","登录成功");
                result.put("companyUser",users);
            }else{
                result.put("code",500);
                result.put("msg","手机验证码输入错误");
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return R.ok().put("result", result);
    }


    /**
     * 用户发送验证码
     * @param map
     * @return
     */
    @PostMapping("/sendCode")
    public R sendCode(@RequestParam Map<String, Object> map){
        //初始化返回值
        Map<String, Object> result = new HashMap<>();
        //获取手机号
        String mobile= map.get("mobile").toString();//？？？
        try{
            //给手机发送验证码 ,调用了ALiSMSUtil，阿里云短信工具
            String code = ALiSMSUtil.sendCode(mobile);
            //将验证码存入到map中,调用了phoneMap，这个是公司里的方法
            phoneMap.put(mobile,code);
            result.put("msg","发送验证码成功");
            result.put("code",200);
        }catch (Exception ex){
            ex.printStackTrace();
            result.put("msg","发送验证码失败");
            result.put("code",500);
        }
        return R.ok().put("result", result); //第一个result是前端接收的，第二个是这里的
    }


    /**
     * 用户注册
     * @param map
     * @return
     */
    @PostMapping("/registerUser")
    public R registerUser(@RequestParam Map<String, Object> map){
        //初始化返回值
        Map<String, Object> result = new HashMap<>();
        //根据用户名查询用户
        UserEntity users =  userService.getOne(new QueryWrapper<UserEntity>().eq("account_name",map.get("accountName").toString()));
        //users不为空，即该用户已经注册过
        if(users != null){
            result.put("code",500);
            result.put("msg","该用户名已经注册过");
            return R.ok().put("result", result);
        }
        users =  userService.getOne(new QueryWrapper<UserEntity>().eq("mobile",map.get("mobile").toString()));
        //users不为空，即该用户已经注册过
        if(users != null){
            result.put("code",500);
            result.put("msg","该手机号已经注册过");
            return R.ok().put("result", result);
        }
        //初始化用户
        UserEntity user = new UserEntity();
        //设置用户名,
        user.setAccountName(map.get("accountName").toString());
        //设置密码DigestUtils:用来给密码加密的
        user.setPassword(DigestUtils.sha256Hex(map.get("password").toString()));
        //设置手机号
        user.setMobile(map.get("mobile").toString());
        //设置注册时间  new Date()为当前时间
        user.setAddtime(new Date());
        //保存用户信息
        boolean res= userService.save(user);
        if(res){
            //注册成功
            result.put("code",200);
            result.put("msg","注册成功");
        }else{
            //注册失败
            result.put("code",500);
            result.put("msg","注册失败");
        }
        return R.ok().put("result", result);
    }
}
